﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using XSTDZ.ERP.Application.DataContracts;
using XSTDZ.ERP.Application;
using XSTDZ.ERP.Infrastructure;
using XSTDZ.ERP.WebApp.Models;
using XSTDZ.ERP.Core.Extentions;
using XSTDZ.ERP.WebApp.Models.Ado;
using XSTDZ.ERP.Infrastructure.Authentication;

namespace XSTDZ.ERP.WebApp.Controllers
{
    //损溢报告
    public class ProfitAndLossController : Controller
    {
        private readonly IProfitAndLossBillService operationServiceImpl = ServiceLocator.Instance.GetService<IProfitAndLossBillService>();	

        public ActionResult Index()
        {
            ViewBag.orgCode = SystemConfig.ChengDuCode;
            return View();
        }
        #region 查看详细
        [NoAuthorizated("Detail")]
        public ActionResult Detail(Guid id)
        {
            var billModel = operationServiceImpl.GetProfitAndLossBill(id);
            return View(billModel);
        }
        #endregion
        #region 添加损溢
        [NoAuthorizated("Add")]
        public ActionResult Add(string orgCode,Guid?id)
        {
            
            ProfitAndLossBillDto billModel = null;
           
            if (id == null || !id.HasValue)
            {
                var NO = new BusinessBillNoCreator().CreateProfitAndLossNextNO();
               var initSysData= DataInit.GetOrgAndDefaultWareHourse(orgCode);//初始化默认组织机构和仓库
                var wareHouse=initSysData.Values.FirstOrDefault();

                billModel = new ProfitAndLossBillDto { 
                    ProfitAndLossNo = NO,
                    StorehouseName = wareHouse.StorehouseName,
                    StorehouseID = wareHouse.Id
                };
                ViewBag.BillId = "";



            }
            else
            {
                Guid billId ;
                Guid.TryParse(id.ToString(),out billId);
                billModel = operationServiceImpl.GetProfitAndLossBill(billId);
               ViewBag.BillId = billId.ToString();
            }
            ViewBag.TempId = Guid.NewGuid();
            ViewBag.orgCode = orgCode;

            return View(billModel);
            
        }
        [HttpPost]
        [NoAuthorizated("Add")]
        public ActionResult Add(ProfitAndLossBillDto roductInBillDto)
        {
            ViewBag.orgCode = Request.Form["HidOrgCode"];

            #region 弹出框数据获取
            var model = new ProductCheckBillModel();
            //仓库ID
            var whId=model.GetRequestFormValues(this.HttpContext,"StorehouseName_val");
            if(!Guid.Empty.Equals(whId))
            {
              roductInBillDto.StorehouseID =whId;
            }
            #endregion
            #region 主数据行处理
            roductInBillDto.CreateID = UserModel.GetLoginUserId(this.HttpContext);
	        #endregion
            #region 明细行数据处理


            var result = Request.Form["hidProductBillItems"];
            var detailItems = model.ConvertJosnToClass<ProfitAndLossBillDetailDto>(result);
            if (!string.IsNullOrEmpty(result) && detailItems == null)
            {
                return Content("-1");//明细行异常
            }
            var checkId = Guid.Empty;
            if (roductInBillDto.Id != null && !roductInBillDto.Id.Equals(Guid.Empty))
            {
                checkId = roductInBillDto.Id;
            }
            detailItems.Each(item =>
            {
                item.ProfitAndLossBillID = checkId;
                if (item.ID == null || item.ID.Equals(Guid.Empty))
                {
                    item.ID = Guid.Empty;
                }
            });

	        #endregion
            #region 数据验证
            if (detailItems == null || detailItems.Count <= 0)
            {
                ModelState.AddModelError("", "必须至少存在一个明细行！");
            }
            #endregion
            if (ModelState.IsValid)
            {
                try
                {
                    if (roductInBillDto.Id != null && !roductInBillDto.Id.Equals(Guid.Empty))
                    {
                        this.operationServiceImpl.UpdateProfitAndLossBill(roductInBillDto, detailItems);
                    }
                    else
                    {
                        operationServiceImpl.AddProfitAndLossBill(roductInBillDto, detailItems);
                    }
                }
                catch (Exception ex)
                {
                    return Content("0");
                }
               
               // ViewBag.PostState = 9;
                return Content("9");
            }

            return Content("0");
        }
        #endregion
        #region 审核
        [NoAuthorizated("Audit")]
        public ActionResult Audit(Guid billId)
        {
            if(!billId.Equals(Guid.Empty))
            {
                try
                {
                    Guid loginUserID = UserModel.GetLoginUserId(this.HttpContext);
                    this.operationServiceImpl.Audit(billId, loginUserID, true);
                    return Content("9");
                }
                catch (Exception ex)
                {
                    return Content("-1");
                }
            }
            return Content("0");
        }
        #endregion
        #region 提交
        [NoAuthorizated("Confirm")]
        public ActionResult Confirm(Guid billId)
        {
            if(!billId.Equals(Guid.Empty))
            {
                Guid loginUserID = UserModel.GetLoginUserId(this.HttpContext);
                this.operationServiceImpl.Confirm(billId, loginUserID);
                return Content("9");
            }
            return Content("0");
        }
        #endregion
        #region 更新至库存
        [NoAuthorizated("UpdateToStock")]
        public ActionResult UpdateToStock(Guid billId, string ids)
        {

            if (ids != "all" && ids.Trim().Length > 0)
            {
                string[] arrayIds = ids.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                var guidIds = new List<Guid>();
                arrayIds.Each(id => guidIds.Add(Guid.Parse(id)));
                operationServiceImpl.UpdateToStock(billId, guidIds);
                return Content("9");
            }
            return Content("0");
        }
        #endregion
        #region 删除订单明细（假删除）
         [NoAuthorizated("Delete")]
        public ActionResult Delete(Guid billId,string ids)
        {
            
            if (ids!="all"&&ids.Trim().Length > 0)
            {
                string[] arrayIds = ids.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                var guidIds = new List<Guid>();
                arrayIds.Each(id => guidIds.Add(Guid.Parse(id)));
                operationServiceImpl.ConvertProfitAndLossBillDeleteState(billId, guidIds);
                return Content("9");
            }
            else
            {
                operationServiceImpl.ConvertProfitAndLossBillDeleteState(billId);
                return Content("9");
            }
            
            return Content("0");
        }
        #endregion
        #region 获取损溢列表数据
        //暂时获取所有数据
        [NoAuthorizated("GetJsonOfDatas")]
        public ActionResult GetJsonOfDatas()
        {
            #region EF的查询，效率低下，故暂时放弃不用
            /*
            var productBills = operationServiceImpl.GetProfitAndLossBills(1, 100);
            if (productBills != null && productBills .Count() != 0)
            {
                var jsonResult = productBills.Select(u =>
                {
                    u.DeleteState = u.Deleted == 0 ? "正常" : "已删除";
                    u.SettleState = u.IsSettle > 0 ? "已结算" : "未结算";
                    u.CheckStateName = u.CheckState > 0 ? "已审核" : "未审核";
                    return u;
                });
                var target = Newtonsoft.Json.JsonConvert.SerializeObject(jsonResult);
                target = "{\"Rows\":" + target + ",\"Total\":\"" + productBills.Count()+ "\"}";
                return Content(target);
            }
            return Content("");
            */
            #endregion
            return Content(new BLLQuery().GetProfitAndLossBills(this.HttpContext));
        }
        /// <summary>
        /// 根据损溢ID，获得损溢所有明细（不包括删除行）
        /// </summary>
        /// <param name="billId"></param>
        /// <returns></returns>
        [NoAuthorizated("GetJsonOfBillDetails")]
        public ActionResult GetJsonOfBillDetails(Guid billId)
        {
            #region EF的查询，效率低下，故暂时放弃不用
            //var billDetails = operationServiceImpl.GetProfitAndLossBillDetails(billId).Where(p => p.Deleted == 0).ToList();
            //if (billDetails != null && billDetails.Count() != 0)
            //{
            //    var jsonResult = billDetails.Select(b => { b.DeleteState = b.Deleted == 0 ? "正常" : "已删除"; return b; });
            //    var target = Newtonsoft.Json.JsonConvert.SerializeObject(jsonResult);
            //    target = "{\"Rows\":" + target + ",\"Total\":\"" + billDetails.Count() + "\"}";
            //    return Content(target);
            //}
            // return Content("");
            #endregion
            if (!billId.Equals(Guid.Empty))
            {
                return Content(new BLLQuery().GetProfitAndLossDetails(billId));
            }
            else
            {
                return Content("");
            }
           
        }
        #endregion
        #region 深圳业务
        public ActionResult SZIndex()
        {
            ViewBag.orgCode = SystemConfig.ShengZhenCode;
            return View("Index");
        }


        #endregion
    }
}
